<?php
/**
 * 创建人 : Forpastime
 * 创建时间: 2023/3/31 15:53
 * 个人主页 : http://forpastime.com
 */

namespace App\Service;


use App\Model\File;
use App\Model\FileCategory;
use Hyperf\Di\Annotation\Inject;
use function Swoole\Coroutine\Http\request;

class FileService
{
    /**
     * @Inject()
     * @var File
     */
    protected $file;

    /**
     * @var FileCategory
     * @Inject()
     */
    protected $fileCategory;
    public function getList($where=[],$field='*',$limit=12)
    {
        $field = for_field_str_to_array($field);
        $list = $this->file->getList($where,$field,$limit);
        foreach ($list as $k=>$v){
            $list[$k]['url'] = for_image_url_style($v);
        }
        return $list;
    }

    public function del($ids)
    {
        return $this->file->del($ids);
    }

    public function getOne($where)
    {
        return $this->file->getOne($where);
    }

    /**
     * 检查文件是否存在
     * @param $data
     * @return array|bool
     */
    public function checkExist($data)
    {
        $exist = $this->file->getOne($data,['id','url','name']);

        if(!empty($exist)){
            $this->file->updateOne([['id','=',$exist['id']]],['updated_at'=>time(),'status'=>1]);
            return $exist;
        }
    }
    public function add($data)
    {
        //获取文件md5，如果没有则添加
        $data['updated_at'] = $data['created_at'] = time();
        return $this->file->add($data);
    }

    /**
     * 添加分类
     * @param $data
     * @return int
     */
    public function addCategory($data)
    {
        if(isset($data['id'])&& !empty($data['id'])){
            $res = $this->fileCategory->where('id',$data['id'])->update($data);
        }else{
            $res = $this->fileCategory->insertGetId($data);
        }
        return $res;
    }

    /**
     * 获取分类分页数据集
     * @param array $where
     * @param int $limit
     * @return array|mixed
     */
    public function getAllCategory($where = [],$limit=10)
    {
        $res = $this->fileCategory->where($where)->paginate($limit);
        if(!empty($res)){
            return for_paginator_data_formater($res);
        }else{
            return [];
        }
    }
    public function getCategory($where = [])
    {
        $res = $this->fileCategory->where($where)->select()->get();

        if(!empty($res)){
            return $res->toArray();
        }else{
            return [];
        }
    }
}